<template>
  <div class="dashboard-container">
    <div class="app-container">
      <el-card>
        <!-- tabs 标签页 -->
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <!-- 新增角色按钮 -->
            <el-row style="height:60px">
              <el-button
                icon="el-icon-plus"
                size="small"
                type="primary"
                @click="showDialog = true"
              >新增角色</el-button>
            </el-row>
            <!-- 表格 -->
            <!-- border 给表格添加边框，label属性代表是每一列标题 -->
            <el-table border="" :data="list">
              <el-table-column align="center" label="序号" width="120" type="index" :index="indexMethods" />
              <el-table-column align="center" label="角色名称" prop="name" width="240" />
              <el-table-column align="center" label="描述" prop="description" />
              <el-table-column align="center" label="操作">
                <template slot-scope="{row}">
                  <el-button size="small" type="success" @click="assignPermission(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click="editRole(row.id)">编辑</el-button>
                  <el-button size="small" type="danger" @click="deleteRole(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-row type="flex" justify="end" align="middle" style="height: 60px">
              <span class="demonstration">共{{ page.total }}条</span>
              <!-- 分页组件 -->
              <!-- current-page 代表的是当前页 page-size代表的是每页的条目数 total：总条目数-->
              <el-pagination layout="prev,pager,next" background :total="page.total" :page-size="page.pagesize" :current-page="page.page" @current-change="changePage" />
            </el-row>
          </el-tab-pane>
          <el-tab-pane label="公司信息">
            <!-- 警告标签， show-icon 展示图标 closeable属性控制标签是否可关闭 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- label-width 代表的是输入框标题的宽度 -->
            <el-form label-width="120px" style="margin-top:50px">
              <el-form-item label="公司名称">
                <el-input v-model="formData.name" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input v-model="formData.companyAddress" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input v-model="formData.mailbox" disabled style="width:400px" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="formData.remarks" type="textarea" :rows="3" disabled style="width:400px" />
              </el-form-item>
            </el-form>
          </el-tab-pane>

        </el-tabs>
      </el-card>
    </div>
    <!-- 弹层 -->
    <el-dialog title="编辑弹层" :visible="showDialog" @close="btnCancel">
      <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="120px">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" />
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="roleForm.description" />
        </el-form-item>
      </el-form>
      <!-- 底部 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="small" @click="btnCancel">取消</el-button>
          <el-button size="small" type="primary" @click="btnOK">确定</el-button>
        </el-col>
      </el-row>
    </el-dialog>
    <!-- 添加分配权限弹层 -->
    <el-dialog title="分配权限" :visible="showPermDialog" @close="btnPermCancel">
      <!-- 权限是一颗树 -->
      <!-- 将数据绑定到组件上 -->
      <!-- check-strictly 如果为true 那表示父子勾选时  不互相关联 如果为false就互相关联 -->
      <!-- id作为唯一标识 -->
      <!-- show-checkbox 节点是否可被选择 -->
      <el-tree
        ref="permTree"
        :data="permData"
        :props="defaultProps"
        :show-checkbox="true"
        :check-strictly="true"
        :default-expand-all="true"
        :default-checked-keys="permIds"
        node-key="id"
      />
      <!-- 确定 取消 -->
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="small" @click="btnPermOK">确定</el-button>
          <el-button size="small" @click="btnPermCancel">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { getRoleList, getCompanyInfo, deleteRole, getRoleDetail, updateRole, addRole } from '@/api/setting'
import { getPermissionList, assignPerm } from '@/api/permission'
import { tranListToTreeData } from '@/utils'
import { mapGetters } from 'vuex'
export default {
  data() {
    return {
      showPermDialog: false,
      list: [], // 角色列表数组
      // 放置页码相关数据
      page: {
        // 当前页码数
        page: 1,
        // 每页总条数
        pagesize: 5,
        // 记录总数
        total: 0

      },
      formData: {},
      showDialog: false, // 控制弹层显示隐藏的变量
      // 表单数据
      roleForm: {
        name: '',
        description: ''
      },
      // 角色校验规则
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }]
      },
      permData: [], // 专门用来接收权限数据 树形数据
      permIds: [], // 存放角色所拥有的id
      roleId: null, // 存放当前点击角色id
      defaultProps: {
        label: 'name'
      }
    }
  },

  computed: {
    ...mapGetters(['companyId'])

  },
  created() {
    this.getRoleList()
    this.getCompanyInfo()
  },

  methods: {
    // 序号计算
    indexMethods(index) {
      return (this.page.page - 1) * this.page.pagesize + index + 1
    },
    async getRoleList() {
      const { total, rows } = await getRoleList(this.page)
      this.page.total = total
      this.list = rows
    },
    async getCompanyInfo() {
      this.formData = await getCompanyInfo(this.companyId)
    },
    // 监听当前页码的变化
    changePage(val) {
      // console.log(val)
      this.page.page = val // 更新当前页码数
      this.getRoleList() // 调用接口，更新数据
    },
    // 删除角色
    async deleteRole(id) {
      // console.log(id)
      try {
        await this.$confirm('确认删除码？是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        await deleteRole(id)
        this.$message.success('删除成功')
        this.getRoleList() // 删除之后，调用接口更新数据
        this.page.page = 1
      } catch (error) {
        this.$message.warning('取消删除')
        console.log(error)
      }
    },
    // 显示弹层
    async editRole(id) {
      this.roleForm = await getRoleDetail(id) // 实现数据回填
      this.showDialog = true
    },
    // 关闭弹层
    btnCancel() {
      this.roleForm = {
        name: '',
        description: ''
      }
      // 移除校验
      this.$refs.roleForm.resetFields()
      this.showDialog = false
    },
    // 点击确定的时候进行自定义校验
    async btnOK() {
      try {
        // 只有校验通过的情况下，才会执行await 下面的代码
        // validate 方法没有回调函数，会返回一个promise
        await this.$refs.roleForm.validate()
        if (this.roleForm.id) {
          // 编辑
          await updateRole(this.roleForm)
        } else {
          // 新增
          // console.log(11)
          await addRole(this.roleForm)
        }
        this.$message.success('操作成功')
        this.getRoleList()
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    btnPermCancel() {
      this.showPermDialog = false
      this.permIds = [] // 清空默认权限
    },
    async btnPermOK() {
      // console.log(this.$refs.permTree.getCheckedKeys(), 12131)
      // this.$refs.permTree.getCheckedKeys()
      // 通过el-tree 组件中的getCheckedKeys方法可以获取所勾选的权限，是个数组
      await assignPerm({ permIds: this.$refs.permTree.getCheckedKeys(), id: this.roleId })
      this.$message.success('分配权限成功')
      this.showPermDialog = false
    },
    // 点击编辑权限按钮
    async assignPermission(roleId) {
      const res = await getPermissionList()
      // console.log(res)
      this.roleId = roleId
      this.permData = tranListToTreeData(res, '0') // 转换成树形数据
      // 调用角色详情接口，接口返回的数据里面有该角色所有的权限数据
      const { permIds } = await getRoleDetail(roleId)
      this.permIds = permIds
      // console.log(this.permIds)
      this.showPermDialog = true
    }
  }

}
</script>

<style>

</style>
